const db = require("../db/index");
// 导入加密中间件
const bcrypt = require("bcryptjs");
const crypto = require("crypto");
const fs = require("fs");

const companyController = {
  // 上传轮播图
  uploadSwiper: async (req, res) => {
    let { set_name } = req.body;
    let oldName = req.files[0].filename;
    let newName = Buffer.from(req.files[0].originalname, "latin1").toString(
      "utf-8"
    );
    fs.renameSync("./public/upload/" + oldName, "./public/upload/" + newName);
    const sql = "UPDATE company SET set_value = ? WHERE set_name = ?";
    try {
      await db.query(sql, [
        `http://127.0.0.1:3000/upload/${newName}`,
        set_name,
      ]);
    } catch (err) {
      return res.cc(err);
    }
    res.send({
      status: 1,
      message: "上传成功",
    });
  },
  // 获取轮播图
  getAllSwiper: async (req, res) => {
    const sql = "SELECT * FROM company WHERE set_name like 'swiper%' ";
    try {
      const [data] = await db.query(sql);
      res.send({
        status: 1,
        message: "获取成功",
        data: data,
      });
    } catch (err) {
      return res.cc(err);
    }
  },
  // 获取公司名称
  getCompanyName: async (req, res) => {
    const sql = "SELECT * FROM company WHERE set_name like '公司名称' ";
    try {
      const [data] = await db.query(sql);
      res.send({
        status: 1,
        message: "获取成功",
        data: data[0].set_value,
      });
    } catch (err) {
      return res.cc(err);
    }
  },
  // 修改公司名称
  setCompanyName: async (req, res) => {
    const { set_value } = req.body;
    console.log(set_value);

    const sql =
      "UPDATE company SET set_value = ? WHERE set_name like '公司名称'";
    try {
      await db.query(sql, set_value);
    } catch (err) {
      return res.cc(err);
    }
    res.send({
      status: 1,
      message: "修改成功",
    });
  },
  // 修改公司信息
  setCompanyInfo: async (req, res) => {
    const { set_value, set_name } = req.body;
    const sql = "UPDATE company SET set_value = ? WHERE set_name LIKE ?";
    try {
      await db.query(sql, [set_value, set_name]);
    } catch (err) {
      return res.cc(err);
    }
    res.send({
      status: 1,
      message: "修改成功",
    });
  },
  // 获取公司信息
  getCompanyInfo: async (req, res) => {
    const sql = "SELECT * FROM company WHERE set_name like '公司%' ";
    try {
      const [data] = await db.query(sql);
      res.send({
        status: 1,
        message: "获取成功",
        data: data,
      });
    } catch (err) {
      return res.cc(err);
    }
  },
};

module.exports = companyController;
